package util

import (
	"errors"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
)

func MatchedFile(src string) string {
	var realSrc string
	if strings.HasSuffix(src, "*") {
		dir := filepath.Dir(src)
		name := filepath.Base(src)
		filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
			if !info.IsDir() {
				matched, _ := filepath.Match(name, info.Name())
				if matched {
					realSrc = path
					return errors.New("Found")
				}
			}
			return nil
		})
	} else {
		realSrc = src
	}
	return realSrc
}

func Copy(src string, dst string) {
	// Read all content of src to data
	var realSrc string
	realSrc = MatchedFile(src)
	data, err := ioutil.ReadFile(realSrc)
	checkErr(err)
	// Write data to dst
	dstDir := filepath.Dir(dst)
	err = os.MkdirAll(dstDir, 0700)
	if err == nil {
		err = ioutil.WriteFile(dst, data, 0644)
	}
	checkErr(err)
}

func checkErr(err error) {
	if err != nil {
		log.Fatal(err)
	}
}
